Page({
    data: {
        // 统一字段命名，与clickConsult保持一致
        counselorId: 0,
        counselorGradeId: 0,
        subscribeConsultTime: "",  // 与clickConsult相同的字段名
        situationDescription: "",  // 与clickConsult相同的字段名
        userId: null,  // 初始化为null，与clickConsult保持一致
        consultantInfo: {},
        loading: true,
        errorMsg: "",
        baseUrl: 'http://localhost:8080'  // 基础URL配置
    },

    onLoad(options) {
        // 1. 获取缓存中的用户ID
        const userId = wx.getStorageSync('userId');
        if (userId) {
            this.setData({
                userId: userId
            });
        } else {
            // 如果没有用户ID，提示登录并跳转到登录页
            wx.showToast({
                title: '请先登录',
                icon: 'none'
            });
            setTimeout(() => {
                wx.navigateTo({
                    url: `/pages/login/login?url=${encodeURIComponent(this.route)}`
                });
            }, 1500);
            return;
        }

        // 2. 接收并验证参数（已能正确接收desc并赋值给situationDescription）
        const {
            counselorId,
            counselorGradeId,
            selectedDate,
            desc
        } = options;

        const validCounselorId = parseInt(counselorId) || 0;
        const validGradeId = parseInt(counselorGradeId) || 0;
        
        // 初始化默认日期
        const today = new Date();
        const year = today.getFullYear();
        const month = (today.getMonth() + 1).toString().padStart(2, '0');
        const day = today.getDate().toString().padStart(2, '0');
        const defaultDate = `${year}-${month}-${day}`;
        
        const validDate = selectedDate || defaultDate;
        const validDesc = desc ? decodeURIComponent(desc) : ""; // 解码情况说明

        this.setData({
            counselorId: validCounselorId,
            counselorGradeId: validGradeId,
            subscribeConsultTime: validDate,
            situationDescription: validDesc, // 赋值情况说明
        });

        // 3. 校验必要参数
        if (validCounselorId === 0) {
            this.showError('参数异常，请返回重试');
            setTimeout(() => wx.navigateBack(), 1500);
            return;
        }

        // 4. 获取咨询师详情
        this.getConsultantDetail();
    },

    // 获取咨询师详情
    getConsultantDetail() {
        const {
            counselorId,
            baseUrl
        } = this.data;
        
        wx.showLoading({
            title: '加载中...'
        });

        wx.request({
            url: `${baseUrl}/counselor/${counselorId}`,
            method: 'GET',
            success: (res) => {
                console.log("咨询师详情接口返回：", res.data);
                if (res.data && res.data.code === 200) {
                    const info = res.data.data || {};

                    // 确保头像URL完整
                    if (info.headImageUrl && !info.headImageUrl.startsWith('http')) {
                        info.headImageUrl = `${baseUrl}${info.headImageUrl}`;
                    }

                    this.setData({
                        consultantInfo: info
                    });
                } else {
                    this.showError('获取咨询师信息失败');
                }
            },
            fail: (err) => {
                console.error('网络请求失败:', err);
                this.showError('网络异常，请稍后重试');
            },
            complete: () => {
                wx.hideLoading();
                this.setData({
                    loading: false
                });
            }
        });
    },

    // 显示错误信息
    showError(msg) {
        this.setData({
            errorMsg: msg
        });
        wx.showToast({
            title: msg,
            icon: 'none'
        });
    },

    // 确认预约
    onSubmit() {
        const {
            counselorId,
            subscribeConsultTime,
            situationDescription,
            userId,
            baseUrl
        } = this.data;

        // 验证用户ID
        if (!userId) {
            this.showError('用户信息异常，请重新登录');
            return;
        }

        // 验证咨询师ID
        if (!counselorId || counselorId === 0) {
            this.showError('咨询师信息异常');
            return;
        }

        // 验证预约时间
        if (!subscribeConsultTime) {
            this.showError('请选择预约时间');
            return;
        }

        // 验证情况说明（现在能获取到值，不会再误判）
        if (!situationDescription || !situationDescription.trim()) {
            this.showError('请输入情况说明');
            return;
        }

        // 提交预约请求
        wx.request({
            url: `${baseUrl}/subscribeConsult`,
            method: 'POST',
            data: {
                userId: userId,
                counselorId: counselorId,
                subscribeConsultTime: subscribeConsultTime,
                situationDescription: situationDescription
            },
            success: (res) => {
                console.log("预约接口返回结果：", res.data);
                if (res.data && res.data.code === 200) {
                    wx.showToast({
                        title: '预约成功',
                        icon: 'success'
                    });
                    setTimeout(() => wx.navigateBack({
                        delta: 2
                    }), 1500);
                } else {
                    this.showError(res.data?.message || '预约失败');
                }
            },
            fail: (err) => {
                console.error('预约请求失败:', err);
                this.showError('网络异常，请稍后重试');
            }
        });
    },
});
